﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using ActiveRecordSample.Entities;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework;
using Castle.ActiveRecord.Framework.Config;
using NHibernate.Expression;
using NHibernate.SqlCommand;

namespace ActiveRecordSample.Driver
{
   class Program
   {
      static void Main(string[] args)
      {
         //XmlConfigurationSource source = new XmlConfigurationSource("appconfig.xml");
         IConfigurationSource config = ActiveRecordSectionHandler.Instance;

         Assembly assembly = Assembly.GetAssembly(typeof (Address));
         ActiveRecordStarter.Initialize(assembly, config);

         GetAllAddresses();
         GetCustomer();
         GetOrdersForCustomer();
         Console.ReadLine();
      }
      private static void GetAllAddresses()
      {
         IList <Address> addresses = Address.FindAll();
         PrintAddress(addresses);
      }

      private static void PrintAddress(IList<Address> addresses)
      {
         foreach (Address address in addresses)
         {
            Console.WriteLine("AddressID: {0}, Street :{1}, City: {2}, State: {3}, Postal Code: {4}",
                              address.AddressID, 
                              address.AddressLine1 + address.AddressLine2,
                              address.City, address.StateProvince, address.PostalCode);
         }
      }

      private static void GetCustomer()
      {
         using (new SessionScope())
         {
            Customer customer = Customer.GetByPrimaryKey(2);
            Console.WriteLine("Customer ID :{0}, First Name {1}, Last Name {2}", customer.CustomerID, customer.FirstName, customer.LastName);
            PrintAddress(customer.Addresses);   
         }
         
      }

      private static void GetOrdersForCustomer()
      {
         using (new SessionScope())
         {           
            DetachedCriteria criteria = DetachedCriteria.For<SalesOrderHeader>();
            criteria.CreateAlias("BelongsToCustomer", "customer", JoinType.InnerJoin).
               Add(Expression.Eq("customer.CustomerID", 16));
            IList<SalesOrderHeader> orders = SalesOrderHeader.FindAll(criteria);
            foreach (var order in orders)
            {
               Console.WriteLine("OrderID : {0}, OrderDate : {1}, CustomerID {2}",order.SalesOrderID, order.OrderDate, order.BelongsToCustomer.CustomerID);
            }
            //ObjectDumper.Write(orders,1);
         }

      }
   }

   
}
